package com.example.wanbaqian.activity;

import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v7.app.AlertDialog;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.view.ViewGroup;
import android.widget.EditText;
import android.widget.TextView;

import com.example.wanbaqian.R;
import com.example.wanbaqian.utils.ActivityManagerUtils;
import com.google.gson.Gson;
import com.example.wanbaqian.base.BaseActivity;
import com.example.wanbaqian.config.CommonValue;
import com.example.wanbaqian.base.HttpCallback;
import com.example.wanbaqian.config.HttpURL;
import com.example.wanbaqian.bean.Info;
import com.example.wanbaqian.bean.UserInfoBean;
import com.example.wanbaqian.customView.CustomImageView;
import com.example.wanbaqian.utils.BaseUtils;
import com.example.wanbaqian.utils.GetJsonUtils;
import com.example.wanbaqian.utils.HttpUtils;
import com.example.wanbaqian.utils.ImageCompressUtil;
import com.example.wanbaqian.utils.JsonUtils;
import com.example.wanbaqian.utils.SPUtils;
import com.zhy.autolayout.AutoRelativeLayout;

import java.io.File;
import java.util.ArrayList;

import butterknife.BindView;
import butterknife.OnClick;
import me.iwf.photopicker.PhotoPicker;

/**
 * 用户信息
 */
public class UserInfoActivity extends BaseActivity implements HttpCallback {
    private static final String TAG = "UserInfoActivity";
    @BindView(R.id.UserInfo_userIcon)
    CustomImageView UserInfoUserIcon;
    @BindView(R.id.UserInfo_userIconLayout)
    AutoRelativeLayout UserInfoUserIconLayout;
    @BindView(R.id.UserInfo_userMobile)
    TextView UserInfoUserMobile;
    @BindView(R.id.UserInfo_userMobileLayout)
    AutoRelativeLayout UserInfoUserMobileLayout;
    @BindView(R.id.UserInfo_NickName)
    TextView UserInfoNickName;
    @BindView(R.id.UserInfo_NickNameLayout)
    AutoRelativeLayout UserInfoNickNameLayout;
    AlertDialog.Builder builder;
    AlertDialog alertDialog;
    private View editTextView = null;
    private EditText editText;
    private UserInfoBean bean;
    private String nickName;
    private Handler handler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            switch (msg.what) {
                case CommonValue.REQUEST_CODE1:
                    HttpUtils.getInstance().postFile(HttpURL.IMAGE_UPLOAD, mContext, CommonValue.user_avatar, new File(msg.obj.toString()),
                            CommonValue.REQUEST_CODE2, UserInfoActivity.this);
                    break;
            }
        }
    };
    @Override
    protected int getLayout() {
        return R.layout.activity_user_ifno;
    }

    @Override
    protected void initView(Bundle savedInstanceState) {
        setStatusBarColor(R.color.main_color);
        setToolBar("个人资料");
        builder = new AlertDialog.Builder(this);
        editTextView = getLayoutInflater().inflate(R.layout.item_edittext, null);
        editText = (EditText) editTextView.findViewById(R.id.item_EditText);
        builder.setView(editTextView);
        mToolbar.setNavigationOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                finish();
            }
        });
    }

    @Override
    protected void initDate() {
        bean = SPUtils.getUserInfo(mContext);
        Log.i(TAG, "initDate: "+bean.toString());
        Log.i(TAG, "initDate: " + bean.getAvatar_url());
        BaseUtils.loadImageForUserIcon(mContext, bean.getAvatar_url(), UserInfoUserIcon);
        UserInfoUserMobile.setText(bean.getLogin_mobile());
        UserInfoNickName.setText(bean.getNick_name());
    }

    @OnClick({R.id.UserInfo_userIconLayout, R.id.UserInfo_userMobileLayout, R.id.UserInfo_NickNameLayout,R.id.setting_exitLogin})
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.UserInfo_userIconLayout:
                PhotoPicker.builder()
                        .setPhotoCount(1)
                        .setShowCamera(true)
                        .setShowGif(false)
                        .setPreviewEnabled(false)
                        .start(this, PhotoPicker.REQUEST_CODE);
                break;
            case R.id.UserInfo_userMobileLayout:
                break;
            case R.id.UserInfo_NickNameLayout:
                showDialog("昵称");
                break;
            case R.id.setting_exitLogin:
                HttpUtils.getInstance().post(GetJsonUtils.getInstance().getRequest(HttpURL.USER_LOGOUT, mContext,
                        new String[]{"accessid"}, new String[]{SPUtils.getAccessid(mContext)})
                        , mContext, null, CommonValue.REQUEST_CODE3, this);
                break;
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == RESULT_OK && requestCode == PhotoPicker.REQUEST_CODE) {
            if (data != null) {
                ArrayList<String> photos = data.getStringArrayListExtra(PhotoPicker.KEY_SELECTED_PHOTOS);
                ImageCompressUtil.compressImage(mContext, photos.get(0), new ImageCompressUtil.ProcessImgCallBack() {
                    @Override
                    public void compressSuccess(String imgPath) {
                        Message message = new Message();
                        message.what = CommonValue.REQUEST_CODE1;
                        message.obj = imgPath;
                        handler.sendMessage(message);
                    }
                });
            }
        }
    }

    /**
     * 对话框
     *
     * @param type
     */
    private void showDialog(String type) {
        editText.setHint("请输入" + type);
        alertDialog = builder.setTitle("修改" + type).setPositiveButton("修改", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                nickName = editText.getText().toString();
                if (TextUtils.isEmpty(nickName))
                    showToast("请输入用户名");
                else if(BaseUtils.getLength(nickName)>4){
                    showToast("最多只能输入4个汉字/8个字母");
                }
                else
                    setNickName(nickName);
                ((ViewGroup) editTextView.getParent()).removeView(editTextView);
            }
        }).setNegativeButton("取消", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                showToast("取消修改");
                ((ViewGroup) editTextView.getParent()).removeView(editTextView);
            }
        }).create();
        alertDialog.show();
        alertDialog.setCanceledOnTouchOutside(false);
    }

    private void setNickName(String nickName) {
        HttpUtils.getInstance().post(GetJsonUtils.getInstance().getRequest(HttpURL.USER_NICKSET, mContext,
                new String[]{"accessid", "nick_name"},
                new String[]{SPUtils.getAccessid(mContext), nickName}), mContext, null, CommonValue.REQUEST_CODE1, this);
    }

    @Override
    public void onSuccess(String content, Info info, int requestCode) {
        switch (requestCode) {
            case CommonValue.REQUEST_CODE1:
                bean.setNick_name(nickName);
                UserInfoNickName.setText(nickName);
                SPUtils.setUserInfo(mContext, new Gson().toJson(bean));
                showToast("修改成功");
                break;
            case CommonValue.REQUEST_CODE2:
                String url = JsonUtils.getInstance().getJsonObject(content, "complete_url");
                bean.setAvatar_url(url);
                BaseUtils.loadImageForUserIcon(mContext, url, UserInfoUserIcon);
                SPUtils.setUserInfo(mContext, new Gson().toJson(bean));
                showToast("修改头像成功");
                break;
            case CommonValue.REQUEST_CODE3:
                SPUtils.CleanUserInfo(mContext);
                new Handler().postDelayed(new Runnable() {
                    @Override
                    public void run() {
                        ActivityManagerUtils.getInstance().exit();
                    }
                }, 300);
                break;
        }
    }

    @Override
    public void onCacheSuccess(String content, Info info, int requestCode) {

    }

    @Override
    public void onError(Info info, int requestCode) {
        showToast(info.getMsg());
    }
}
